/**
 * 市场数据状态管理Store
 * ====================
 * 
 * 基于Zustand的实时市场数据状态管理
 * 支持WebSocket数据更新、缓存、订阅管理
 */

import { useEffect } from 'react';
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { WebSocketManager, WebSocketMessage } from '../websocket/WebSocketManager';
import { getMarketDataWebSocketManager } from '../websocket';

export interface MarketData {
  symbol: string;
  price: number;
  change: number;
  changePercent: number;
  volume: number;
  timestamp: number;
  high?: number;
  low?: number;
  open?: number;
  close?: number;
  [key: string]: any;
}

export interface MarketDataState {
  // 数据存储
  data: Record<string, MarketData>;
  subscriptions: Set<string>;
  
  // 连接状态
  isConnected: boolean;
  connectionError: string | null;
  
  // 统计信息
  lastUpdate: Record<string, number>;
  updateCount: Record<string, number>;
  
  // WebSocket管理器
  wsManager: WebSocketManager | null;
  
  // 动作
  setData: (symbol: string, data: MarketData) => void;
  setBatchData: (data: Record<string, MarketData>) => void;
  subscribe: (symbols: string[]) => void;
  unsubscribe: (symbols: string[]) => void;
  setConnectionStatus: (isConnected: boolean, error?: string) => void;
  initializeWebSocket: (config: any) => void;
  destroyWebSocket: () => void;
  getData: (symbol: string) => MarketData | null;
  getAllData: () => Record<string, MarketData>;
  getSubscriptions: () => string[];
  clearData: () => void;
  reset: () => void;
}

// 初始状态
const initialState = {
  data: {},
  subscriptions: new Set<string>(),
  isConnected: false,
  connectionError: null,
  lastUpdate: {},
  updateCount: {},
  wsManager: null
};

export const useMarketDataStore = create<MarketDataState>()(
  subscribeWithSelector((set, get) => ({
    ...initialState,

    // 设置单个数据
    setData: (symbol: string, data: MarketData) => {
      set((state) => ({
        data: {
          ...state.data,
          [symbol]: {
            ...data,
            timestamp: data.timestamp || Date.now()
          }
        },
        lastUpdate: {
          ...state.lastUpdate,
          [symbol]: Date.now()
        },
        updateCount: {
          ...state.updateCount,
          [symbol]: (state.updateCount[symbol] || 0) + 1
        }
      }));
    },

    // 设置批量数据
    setBatchData: (data: Record<string, MarketData>) => {
      const now = Date.now();
      set((state) => {
        const newData = { ...state.data };
        const newLastUpdate = { ...state.lastUpdate };
        const newUpdateCount = { ...state.updateCount };

        Object.entries(data).forEach(([symbol, marketData]) => {
          newData[symbol] = {
            ...marketData,
            timestamp: marketData.timestamp || now
          };
          newLastUpdate[symbol] = now;
          newUpdateCount[symbol] = (newUpdateCount[symbol] || 0) + 1;
        });

        return {
          data: newData,
          lastUpdate: newLastUpdate,
          updateCount: newUpdateCount
        };
      });
    },

    // 订阅股票代码
    subscribe: (symbols: string[]) => {
      set((state) => {
        const newSubscriptions = new Set(state.subscriptions);
        symbols.forEach(symbol => newSubscriptions.add(symbol));
        
        return { subscriptions: newSubscriptions };
      });

      // 如果WebSocket已连接，发送订阅消息
      const { wsManager } = get();
      if (wsManager?.isConnected()) {
        wsManager.subscribe(symbols);
      }
    },

    // 取消订阅
    unsubscribe: (symbols: string[]) => {
      set((state) => {
        const newSubscriptions = new Set(state.subscriptions);
        symbols.forEach(symbol => newSubscriptions.delete(symbol));
        
        return { subscriptions: newSubscriptions };
      });

      // 如果WebSocket已连接，发送取消订阅消息
      const { wsManager } = get();
      if (wsManager?.isConnected()) {
        wsManager.unsubscribe(symbols);
      }
    },

    // 设置连接状态
    setConnectionStatus: (isConnected: boolean, error?: string) => {
      set({
        isConnected,
        connectionError: error || null
      });
    },

    // 初始化WebSocket
    initializeWebSocket: async (config: any) => {
      const { wsManager } = get();
      if (wsManager) {
        console.warn('WebSocket manager already initialized');
        return;
      }

      // 使用工厂函数获取单例 WebSocketManager（自动使用市场数据配置）
      const manager = await getMarketDataWebSocketManager(
        {
          onConnect: () => {
            get().setConnectionStatus(true);
            // 重新订阅所有股票
            const { subscriptions } = get();
            const manager = get().wsManager;
            if (manager && subscriptions.size > 0) {
              manager.subscribe(Array.from(subscriptions));
            }
          },
          onDisconnect: (code, reason) => {
            get().setConnectionStatus(false, `Disconnected: ${reason}`);
          },
          onMessage: (message: WebSocketMessage) => {
            if (message.type === 'data' && message.data?.symbol) {
              const marketData: MarketData = {
                symbol: message.data.symbol,
                price: message.data.data?.price || 0,
                change: message.data.data?.change || 0,
                changePercent: message.data.data?.changePercent || 0,
                volume: message.data.data?.volume || 0,
                timestamp: message.timestamp,
                high: message.data.data?.high,
                low: message.data.data?.low,
                open: message.data.data?.open,
                close: message.data.data?.close,
                ...message.data.data
              };
              get().setData(message.data.symbol, marketData);
            }
          },
          onError: (error) => {
            console.error('WebSocket error:', error);
            get().setConnectionStatus(false, 'WebSocket error');
          }
        },
        config // 传递用户自定义配置（可选）
      );

      set({ wsManager: manager });
    },

    // 销毁WebSocket
    destroyWebSocket: () => {
      const { wsManager } = get();
      if (wsManager) {
        wsManager.destroy();
        set({ wsManager: null, isConnected: false });
      }
    },

    // 获取单个数据
    getData: (symbol: string) => {
      const { data } = get();
      return data[symbol] || null;
    },

    // 获取所有数据
    getAllData: () => {
      const { data } = get();
      return data;
    },

    // 获取订阅列表
    getSubscriptions: () => {
      const { subscriptions } = get();
      return Array.from(subscriptions);
    },

    // 清空数据
    clearData: () => {
      set({
        data: {},
        lastUpdate: {},
        updateCount: {}
      });
    },

    // 重置状态
    reset: () => {
      const { wsManager } = get();
      if (wsManager) {
        wsManager.destroy();
      }
      set(initialState);
    }
  }))
);

// 选择器函数
export const selectMarketData = (symbol: string) => (state: MarketDataState) => state.data[symbol];
export const selectAllMarketData = (state: MarketDataState) => state.data;
export const selectIsConnected = (state: MarketDataState) => state.isConnected;
export const selectSubscriptions = (state: MarketDataState) => Array.from(state.subscriptions);
export const selectConnectionError = (state: MarketDataState) => state.connectionError;
export const selectLastUpdate = (symbol: string) => (state: MarketDataState) => state.lastUpdate[symbol];
export const selectUpdateCount = (symbol: string) => (state: MarketDataState) => state.updateCount[symbol] || 0;

// 订阅特定股票数据变化的Hook
export function useMarketDataSubscription(symbol: string) {
  return useMarketDataStore(selectMarketData(symbol));
}

// 订阅连接状态的Hook
export function useConnectionStatus() {
  return useMarketDataStore((state) => ({
    isConnected: state.isConnected,
    error: state.connectionError
  }));
}

// 订阅所有市场数据的Hook
export function useAllMarketData() {
  return useMarketDataStore(selectAllMarketData);
}

// 订阅管理Hook
export function useSubscriptionManager() {
  const subscribe = useMarketDataStore((state) => state.subscribe);
  const unsubscribe = useMarketDataStore((state) => state.unsubscribe);
  const subscriptions = useMarketDataStore(selectSubscriptions);
  
  return {
    subscribe,
    unsubscribe,
    subscriptions
  };
}

// 自动初始化WebSocket的Hook
export function useWebSocketInitialization() {
  const initializeWebSocket = useMarketDataStore((state) => state.initializeWebSocket);
  const destroyWebSocket = useMarketDataStore((state) => state.destroyWebSocket);
  const isConnected = useMarketDataStore(selectIsConnected);
  
  useEffect(() => {
    // 组件挂载时初始化WebSocket
    initializeWebSocket({
      reconnectInterval: 5000,
      maxReconnectAttempts: 10,
      heartbeatInterval: 30000
    });
    
    // 组件卸载时销毁WebSocket
    return () => {
      destroyWebSocket();
    };
  }, [initializeWebSocket, destroyWebSocket]);
  
  return { isConnected };
}
